/*
	@发布账号
*/
define(['../common/service','../model/data'],function(http,DATA){
	var account = {
		/*
			@初始化账号区域
			$.prices: 预算出价生成数据
		*/
		init: function(DATA){
			var _this = this;
			_this.cache = DATA.cache;
			_this.temp = DATA.temp;

			//即时获取数据
			_this.doitNow(function(){
				//绑定刷新账号列表事件
				_this.bindRefreshEvent();
				//绑定账号选择事件
				_this.bindCheckAccountEvent();
				//绑定预算出价选择事件
				_this.bindPricesAreaEvent();
				//绑定自定义受众 切换事件
				_this.bindCustomAudienceAreaEvent();
				 //生成账号列表
				_this.initAccount();
			});
		}
		/*
			@绑定预算出价选择事件
			用于重置账号区域
		*/
		,bindPricesAreaEvent: function(){
			var _this = this;
			$('#price-config-field').on('click', 'button[aria-pressed]', function(){
				_this.initAccount();
			});
		}
		/*
			@绑定生成用户定位 事件
			用于重置账号区域

		*/
		,bindCustomAudienceAreaEvent: function(){
			var _this = this;
			$('#gen-custom').bind('initAccount',function(e,temp){
				_this.temp = temp;
				_this.initAccount();
			});
		}
		/*
			@初始化账号区域
			$._entrustAccounts_: 账号组数据
		*/
		,initAccount: function(_entrustAccounts_){
			var _this = this;
			var entrustAccounts = _entrustAccounts_ || _this.cache.entrustAccounts;

			//CPA
			_this.containsCPA = false; //是否包含CPA
			_this.onlyCPA	= true; //是否只有CPA

			//todo verify here
			$.each(DATA.prices, function(i, v){
				$.each(v, function(j, p){
					if (p.billingEvent == "APP_INSTALLS" && p.optimizationGoal == "APP_INSTALLS") {
						_this.containsCPA = true;
					}else {
						_this.onlyCPA = false;
					}
				});
			});

			//自定义受众
			var _emptyNum = 0;  //为空对象的数量
			var isSupportCpa = 'N';
			$.each(_this.cache.entrustAccounts, function(i, v){
				//是否支持CPA
				if (v.isSupportCPA){
					isSupportCpa = 'Y';
				}
				if(!_this.temp.CustomAudience || _this.temp.CustomAudience.length == 0){  //当前为空时
					v.isSupportCustomAudience = true;
				}else{
					v.isSupportCustomAudience = false;
					_emptyNum = 0;
					$.each(_this.temp.CustomAudience, function(i2, v2){
						if(!v2.customAudiences ||v2.customAudiences.length == 0){
							v2.fbAccountId == v.fbAccountId ? v.isSupportCustomAudience = true : '';
							_emptyNum++;
							return;
						}
						else {
							$.each(v2.customAudiences, function(i3, CustomAudienceItem){
								v2.fbAccountId == v.fbAccountId ? v.isSupportCustomAudience = true : '';
							});
						}
					});
					//验证是否全部为空对象
					if(_emptyNum == _this.temp.CustomAudience.length){
						v.isSupportCustomAudience = true;
					}
				}
			});
			DATA.sessionData.isSupportCpa = isSupportCpa;

			var billingEventLis = $('div[name="drop-billingEvent"]').find(".dropdown-menu").find("li");
			var billingEventInfo;
			$.each(billingEventLis, function(i, billingEventLi){
				billingEventInfo = $(billingEventLi).data("data");
				if (typeof billingEventInfo=="object"){
					if ("APP_INSTALLS" == billingEventInfo["id"]){
						if ('Y' == isSupportCpa){
							//支持CPA
							$(billingEventLi).removeClass("disabled");
							$(billingEventLi).find("a").html(I18N.getText('createAd', 'appInstalls'));

						} else {
							//不支持CPA
							$(billingEventLi).addClass("disabled");
							$(billingEventLi).find("a").html(I18N.getText('createAd', 'appInstalls') + I18N.getText('createAd', 'appInstallsNoPermission'));
						}
					}
				}
			});

			var tmp = '';
			$.each(entrustAccounts, function(i, v){
				v.onlyCPA = _this.onlyCPA;
				v.containsCPA = _this.containsCPA;
				tmp += _this.createHtml(v);
			})
			var accountsList =$('#accountsList');
			accountsList.html(tmp);

			//配置账号选择事件
			var acWrap = $('#accountsWrap');
			$(':checkbox:enabled', acWrap).prop("checked", false);
			if(accountsList.find('input[type="checkbox"]').length == accountsList.find(':disabled[type="checkbox"]').length){
				acWrap.find('input[box-type="all"]').attr('disabled','disabled');
			}else{
				acWrap.find('input[box-type="all"]').removeAttr('disabled');
			}
		}
		/*
			@绑定选择账号事件
		*/
		,bindCheckAccountEvent: function(){
			var _this = this;
			var acWrap = $('#accountsWrap');
			acWrap.on('click', ':checkbox:enabled',function(){
				var $el = $(this);
				if ($el.attr('box-type') == 'all') {
					$(":checkbox[box-type=one]:enabled", acWrap).prop("checked", $el[0].checked);
					return;
				}
				var ones = $(":checkbox[box-type=one]:enabled:not(:checked)", acWrap);
				if (!ones.length) {
					$(":checkbox[box-type=all]", acWrap).prop("checked", true);
				} else {
					$(":checkbox[box-type=all]", acWrap).prop("checked", false);
				}
			});
		}
		/*
			@创建DOM
			$._account_: 单个账号
		*/
		,createHtml: function(_account_){
			var _this = this;
			var _statusHtml = '',
				isDisabled = false, //是否不可用
				isRemind = false,	//是否提醒
				cpaRemind = false, //CPA提醒
				numRemind = false; //数量提醒
			var remindVal = 1000,	//空闲数提醒峰值
				disabledVal = 10;  //空闲数禁用峰值
			//账号下Campaign空闲数已达到500或500以下

			//账号不可用
			if(_account_.accountStatus != 1){
				_statusHtml = '(账户待定中)';
				isDisabled = true;
			}
			if(!isDisabled && _account_.objadCampaignCount <= (window.cpDisableNum || disabledVal)){
				_statusHtml = '(账户已满，请先清理Campaign再创建)';
				isDisabled = true;
			}
			//账号下adset空闲数已达到300或300以下
		//	if(adSetCount <= disabledVal){
			if(!isDisabled && _account_.adSetCount <= (window.adsetDisableNum || disabledVal)){
		//		_statusHtml = '(可创建adSetCount:'+ adSetCount +')';
				numRemind = true;
			}
			//不支持 CPA
			if(!isDisabled && _account_.isSupportCPA == 0 && _this.containsCPA && _this.onlyCPA){
				_statusHtml = '(不支持CPA)';
				isDisabled = true;
			}
			if(!isDisabled && _account_.isSupportCPA == 0 && _this.containsCPA && !_this.onlyCPA){
				_statusHtml = '(不支持CPA)';
				isRemind = true;
				cpaRemind = true;
			}
			//是否支持已选自定义受众
			if(!_account_.isSupportCustomAudience ){
				_statusHtml = '(不支持已选自定义受众)';
				isDisabled = true;
			}
			//是否支持相似受眾
			if(!_this.getLookalikeAudienceAgent(_account_)){
				_statusHtml = '(不支持已选相似受众)';
				isDisabled = true;
			}
			var tmpHtml = '<div class="checkbox '+ ( isRemind ? ' acc-remind' : '' )+'" '
						+ ( cpaRemind? ' cpa-remind="true"' : '')
						+ ' '+ ( numRemind? ' num-remind="true"' : '' ) +'>'
						+ '<label>'
						+ '<input type="checkbox" box-type="one" class="checkbox" value="'+ _account_.fbAccountId +'" '
						+ ( isDisabled ? 'disabled':'' )+'>'
						+ '<span class="acc-info" '+ ( isDisabled ? 'disabled':'' ) +'>'
						+ '<span class="acc-name">'
						+ (_account_.displayName ? _account_.displayName : '' )
				        + '</span>&nbsp;&nbsp;<span style="color: #AFAFAF;">' + _account_.fbAccountId
						+ '</span>';
			if(_statusHtml != ''){
				tmpHtml += '&nbsp;<span class="acc-remind">'+ _statusHtml +'</span>';
			}
			tmpHtml +='</span></label></div>';
			return tmpHtml;
		}
		/*
		 @绑定刷新账号列表功能
		 */
		,bindRefreshEvent: function(){
			var _this = this;
			$('body').off('click','#refresh-accounts');
			$('body').on('click','#refresh-accounts',function(){
				var _refreshAction = $(this);
				if(_refreshAction.hasClass('updating')){
					return false;
				}
				_refreshAction.addClass('updating');
				http.do('/cache/refreshCPAAndAdCampLimit', {param: JSON.stringify({cacheId : DATA.cache.cacheId})}).then(function(result){
					DATA.cache.entrustAccounts = result.data.entrustAccounts;
					_this.initAccount();
					window.setTimeout(function(){
						_refreshAction.removeClass('updating');
					},1000);
				});
			});
		}
		/*
			@即时获取账号数据
		*/
        ,doitNow : function(callback){
			var _this = this;
			http.do('/cache/refreshCPAAndAdCampLimit',
					{param: JSON.stringify({cacheId : DATA.cache.cacheId})}).then(function(result){
				DATA.cache.entrustAccounts = result.data.entrustAccounts;
				typeof(callback) == 'function' ? callback() : '';
			});
		}
		/**
		 * 判斷此單個賬號是否存在 所選的相似受眾中，如果沒有則不支持此相似受眾。
		 * @param account 單個賬號
		 * @returns {boolean}
         */
		,getLookalikeAudienceAgent:function(account){
			var flag = false;
			var accountArr = [];
			if(DATA.nowTemp.LookalikeAudience.length != 0){
				$.each(DATA.nowTemp.LookalikeAudience,function(i,o){
					if(typeof o.fbAccountId != "undefined"){
						accountArr.push(o.fbAccountId);
					}
				});
			}
			if(accountArr.length == 0){
            	//當前操作沒有選擇相似受眾，不進行相似受眾賬號判斷
				flag = true;
			}else{
				if($.inArray(account.fbAccountId+"",accountArr) == -1){
					flag = false;
				}else{
					flag = true;
				}
			}
			return flag;
		}
	}
	return account;
});
